<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" th:href="@{/static/bootstrap/bootstrap.min.css}">
    <link rel="stylesheet" th:href="@{/static/css/index.css}">
    <title>index</title>
    <script th:src="@{/static/js/jquery.min.js}"></script>
    <script th:src="@{/static/js/bootstrap.min.js}"></script>
    <script th:src="@{/static/js/vue.js}"></script>
    <script th:src="@{/static/js/axios.min.js}"></script>

    <!--
        Vue + Bootstrap 版本
        作者：@☆*往事随風*☆ https://blog.csdn.net/m0_47214030?spm=1000.2115.3001.5343
   -->

</head>
<body>
<div class="container">
    <!-- 标题 -->
    <div class="row">
        <h1 class="col-md-4 col-md-offset-4">部门管理系统</h1>
    </div>
    <!-- 按钮 -->
    <div class="row">
        <div class="col-md-4 col-md-offset-8">
            <button class="btn btn-primary" id="addEmployee" @click="openAddModal">新增</button>
            <button class="btn btn-danger" @click="deleteEmployeeMore">删除</button>
        </div>
    </div>
    <!-- 员工添加模态框  -->
    <div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="addModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="addModalLabel">添加员工信息</h4>
                </div>
                <div class="modal-body">
                    <form class="form-horizontal" ref="addEmployeeForm">
                        <div class="form-group">
                            <label for="add-employee-name-input" class="col-sm-2 control-label">员工姓名</label>
                            <div class="col-sm-10">
                                <input type="text" name="employeeName" class="form-control" id="add-employee-name-input"
                                       placeholder="请输入真实姓名" @change="checkEmployeeName"
                                       v-model="saveEmployee.employeeName" ref="employeeName">
                                <span class="help-block"></span>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="add-employee-email-input" class="col-sm-2 control-label">员工邮箱</label>
                            <div class="col-sm-10">
                                <input type="email" name="email" class="form-control" id="add-employee-email-input"
                                       placeholder="请输入有效邮箱" v-model="saveEmployee.email" ref="email">
                                <span class="help-block"></span>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">性别</label>
                            <div class="col-sm-10">
                                <label class="radio-inline">
                                    <input type="radio" name="gender" id="add-employee-gender1-input" value="男" checked
                                           v-model="saveEmployee.gender"> 男
                                </label>
                                <label class="radio-inline">
                                    <input type="radio" name="gender" id="add-employee-gender2-input" value="女"
                                           v-model="saveEmployee.gender"> 女
                                </label>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">部门信息</label>
                            <div class="col-sm-4">
                                <select class="form-control" v-model="saveEmployee.departmentId">
                                    <option v-for="department in departments" :key="department.departmentId"
                                            :value="department.departmentId">
                                        {{department.departmentName}}
                                    </option>
                                </select>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" @click="submitEmployee" ref="saveButton">保存</button>
                </div>
            </div>
        </div>
    </div>
    <!-- 修改员工模态框-->
    <div class="modal fade" id="updateModal" tabindex="-1" role="dialog" aria-labelledby="addModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="updateModalLabel">修改员工信息</h4>
                </div>
                <div class="modal-body">
                    <form class="form-horizontal" ref="updateEmployeeForm">
                        <div class="form-group">
                            <label for="update-employee-name-input" class="col-sm-2 control-label">员工姓名</label>
                            <div class="col-sm-10">
                                <input class="form-control-static" id="update-employee-name-input"
                                       v-model="updateEmployee.employeeName" disabled></input>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="update-employee-email-input" class="col-sm-2 control-label">员工邮箱</label>
                            <div class="col-sm-10">
                                <input type="email" name="email" class="form-control" id="update-employee-email-input"
                                       placeholder="请输入有效邮箱" v-model="updateEmployee.email" ref="updateEmail">
                                <span class="help-block"></span>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">性别</label>
                            <div class="col-sm-10">
                                <label class="radio-inline">
                                    <input type="radio" name="gender" id="update-employee-gender1-input" value="男"
                                           checked
                                           v-model="updateEmployee.gender"> 男
                                </label>
                                <label class="radio-inline">
                                    <input type="radio" name="gender" id="update-employee-gender2-input" value="女"
                                           v-model="updateEmployee.gender"> 女
                                </label>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">部门信息</label>
                            <div class="col-sm-4">
                                <select class="form-control" v-model="updateEmployee.departmentId">
                                    <option v-for="department in departments" :key="department.departmentId"
                                            :value="department.departmentId">
                                        {{department.departmentName}}
                                    </option>
                                </select>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" @click="updateEmployees" ref="updateButton">更新
                    </button>
                </div>
            </div>
        </div>
    </div>
    <!--  列表信息-->
    <div class="row">
        <div class="col-md-12">
            <div class="table-responsive">
                <table class="table table-hover table-bordered col-md-12 employee-table">
                    <tr>
                        <th><input type="checkbox" @click="isCheckAll" ref="checkAll"></th>
                        <th>id</th>
                        <th>姓名</th>
                        <th>性别</th>
                        <th>邮箱</th>
                        <th>所在部门</th>
                        <th>操作</th>
                    </tr>
                    <tr v-for="employee in (employees)" :key="employees.employeeId">
                        <td><input type="checkbox" @click="oneCheck" ref="check"></td>
                        <td>{{employee.employeeId}}</td>
                        <td>{{employee.employeeName}}</td>
                        <td>{{employee.gender}}</td>
                        <td>{{employee.email}}</td>
                        <td>{{employee.department.departmentName}}</td>
                        <td>
                            <button class="btn btn-primary" :data-edit-id="employee.employeeId" aria-label="Left Align"
                                    @click="openUpdateModal($event)" ref="updateButton">
                                <span class="glyphicon glyphicon-pencil  btn-sm" aria-hidden="true"></span>
                                编辑
                            </button>
                            <button class="btn btn-danger" aria-label="Left Align" :data-delete-id="employee.employeeId"
                                    @click="deleteEmployeeById($event)">
                                <span class="glyphicon glyphicon-trash  btn-sm" aria-hidden="true"></span>
                                删除
                            </button>
                        </td>
                    </tr>
                </table>
            </div>
        </div>
    </div>
    <!--  分页导航-->
    <div class="row">
        <!-- 分页文字信息 -->
        <div class="col-md-6">
            <sapn>当前页码 {{pageInfo.pageNum}}</sapn>
            <span>总页码 {{pageInfo.pages}} </span>
            <span>总记录数 {{pageInfo.total}} </span>
        </div>
        <!-- 分页导航 -->
        <div class="col-md-6">
            <nav aria-label="Page navigation">
                <ul class="pagination">
                    <li class="firstPage">
                        <a @click="firstPage">首页</a>
                    </li>
                    <li v-show="this.pageInfo.hasPreviousPage" class="previous">
                        <a @click="previous" aria-label="Previous">
                            <span aria-hidden="true">&laquo;</span>
                        </a>
                    </li>
                    <li v-for="navigatePageNumber in (pageInfo.navigatepageNums)"
                        :key="navigatePageNumber"
                        :data-navigate="navigatePageNumber"
                        ref="navigatePageNumberList"
                        class="navigateList">
                        <a @click="navigatePage(navigatePageNumber,$event)">{{navigatePageNumber}}</a>
                    </li>
                    <li v-show="this.pageInfo.hasNextPage" class="next">
                        <a @click="next" aria-label="Next">
                            <span aria-hidden="true">&raquo;</span>
                        </a>
                    </li>
                    <li class="endPage">
                        <a @click="endPage">尾页</a>
                    </li>
                </ul>
            </nav>
        </div>
    </div>
</div>
<script>
    let vm = new Vue({
        el: '.container',
        data: {
            pageNumber: 1,
            pageInfo: {},
            employees: [],
            departments: [],
            saveEmployee: {
                employeeName: '',
                email: '',
                gender: '',
                departmentId: 1
            },
            updateEmployee: {
                employeeId: '',
                employeeName: '',
                email: '',
                gender: '',
                departmentId: 1
            },
        },
        created() {
            axios.get(`http://localhost:8080/SSM/employeeList?pageNumber=${this.pageNumber}`).then(response => {
                // 请求成功更新List的数据
                this.pageInfo = response.data.data.employeePageInfo;
                this.employees = response.data.data.employeePageInfo.list;
            }),
                error => {
                    console.log('请求失败', error.message);
                }
        },
        updated() {
            // 如果当前导航页码等于当前页码，则添加背景样式
            let navigatePageNumbers = this.pageInfo.navigatepageNums;
            let navigates = this.$refs.navigatePageNumberList;
            let temp = null;
            // 将获取到的 分页导航 进行排序（根据 data-navigate 属性由小到大排序）
            for (let i = 0; i < navigates.length - 1; i++) {
                for (let j = 0; j < navigates.length - 1 - i; j++) {
                    if (parseInt(navigates[j].getAttribute("data-navigate")) > parseInt(navigates[j + 1].getAttribute("data-navigate"))) {
                        temp = navigates[j];
                        navigates[j] = navigates[j + 1];
                        navigates[j + 1] = temp;
                    }
                }
            }
            navigatePageNumbers.forEach((value, index) => {
                if (value === this.pageInfo.pageNum) {
                    navigates[index].classList.add("active");
                } else {
                    navigates[index].classList.remove("active");
                }
            });
        },
        methods: {
            // 打开添加员工模态框
            openAddModal() {
                // 清空表单中上次残留的内容和样式
                this.clearForm("saveForm");
                // 发送ajax请求获取部门信息(填充到部门下拉框中)
                axios.get(`http://localhost:8080/SSM/department`).then(response => {
                    this.departments = response.data.data.department;
                    // 打开模态框
                    $("#addModal").modal({
                        backdrop: 'static'
                    });
                }), error => {
                    console.log(error.message);
                }
            },
            // 打开修改员工模态框
            openUpdateModal(event) {
                // 清空表单中上次残留的内容和样式
                this.clearForm("updateForm");
                let employeeId = event.currentTarget.getAttribute('data-edit-id');
                // 发送ajax请求获取员工信息（填充到表单）
                axios.get(`http://localhost:8080/SSM/employee/${employeeId}`).then(response => {
                    let employee = response.data.data.employeeById;
                    console.log(employee);
                    this.updateEmployee.employeeId = employee.employeeId;
                    this.updateEmployee.employeeName = employee.employeeName;
                    this.updateEmployee.email = employee.email;
                    this.updateEmployee.gender = employee.gender;
                    this.updateEmployee.departmentId = employee.departmentId;
                }), error => {
                    console.log(error.message);
                }
                // 发送ajax请求获取部门信息(填充到部门下拉框中)
                axios.get(`http://localhost:8080/SSM/department`).then(response => {
                    this.departments = response.data.data.department;
                    // 打开模态框
                    $("#updateModal").modal({
                        backdrop: 'static'
                    });
                }), error => {
                    console.log(error.message);
                }
            },
            // 清空表单信息
            clearForm(formType) {
                if ("saveForm" === formType) {
                    // 移除保存员工信息表单校验样式 和 文本内容
                    this.$refs.employeeName.parentElement.classList.remove("has-success", "has-error");
                    this.$refs.email.parentElement.classList.remove("has-success", "has-error");
                    this.$refs.employeeName.parentElement.lastChild.textContent = "";
                    this.$refs.email.parentElement.lastChild.textContent = "";
                    // 清空表单内容
                    this.saveEmployee.employeeName = "";
                    this.saveEmployee.email = "";
                    this.saveEmployee.gender = "男";
                    this.saveEmployee.departmentId = 1;
                } else if ("updateForm" === formType) {
                    // 移除修改员工信息表单校验样式
                    this.$refs.updateEmail.parentElement.classList.remove("has-success", "has-error");
                    this.$refs.updateEmail.parentElement.lastChild.textContent = "";
                    // 清空表单内容
                    this.updateEmployee.email = "";
                    this.updateEmployee.gender = "男";
                    this.updateEmployee.departmentId = 1;

                }
            },
            // 校验表单数据
            validateAddForm() {
                let employeeName = vm.saveEmployee.employeeName;
                let email = vm.saveEmployee.email;
                let regName = /(^[a-zA-Z0-9_-]{6,16}$)|(^[\u4e00-\u9fa5]{2,5})/g;
                let regEmail = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/g;
                return {
                    checkEmployeeName: regName.test(employeeName),
                    checkEmail: regEmail.test(email)
                };
            },
            // 输出校验信息
            showValidateMessage(element, status, message) {
                element.parentElement.classList.remove("has-success", "has-error");
                element.parentElement.lastChild.textContent = "";
                if ("success" === status) {
                    element.parentElement.classList.add("has-success");
                    element.parentElement.lastChild.textContent = "";
                } else if ("error" === status) {
                    element.parentElement.classList.add("has-error");
                    element.parentElement.lastChild.textContent = message;
                }
            },
            // 校验用户名是否重复
            checkEmployeeName() {
                axios.get(`http://localhost:8080/SSM/checkEmployeeName?employeeName=${this.saveEmployee.employeeName}`).then(response => {
                    if (response
                        .data.code === 100) {
                        this.showValidateMessage(this.$refs.employeeName, "success", "用户名可用");
                        // 设置保存按钮为可提交状态
                        this.$refs.saveButton.setAttribute("save", true);
                    } else if (response.data.code === 200) {
                        this.showValidateMessage(this.$refs.employeeName, "error", response.data.data.va_message);
                        // 设置保存按钮为不可提交状态
                        this.$refs.saveButton.setAttribute("save", false);
                    }
                }), error => {
                    console.log("error：" + error.message);
                }
            },
            // 保存员工信息
            submitEmployee() {
                // 进行用户名数据校验
                let employeeNameInput = this.$refs.employeeName;
                let emailInput = this.$refs.email;
                if (!this.validateAddForm().checkEmployeeName) {
                    this.showValidateMessage(employeeNameInput, "error", "用户名不合法，用户名可以是2-5位中文或者6-16位英文和数字的组合");
                    return false;
                } else {
                    this.showValidateMessage(employeeNameInput, "success", "");
                }
                // 进行邮箱数据校验
                if (!this.validateAddForm().checkEmail) {
                    this.showValidateMessage(emailInput, "error", "邮箱格式不合法");
                    return false;
                } else {
                    this.showValidateMessage(emailInput, "success", "");
                }
                // 校验按钮是否是可提交状态
                if ('false' === this.$refs.saveButton.getAttribute("save")) {
                    return false;
                }
                axios({
                    url: 'http://localhost:8080/SSM/employee',
                    method: "POST",
                    params: {
                        employeeName: this.saveEmployee.employeeName,
                        email: this.saveEmployee.email,
                        gender: this.saveEmployee.gender,
                        departmentId: this.saveEmployee.departmentId
                    }
                }).then(response => {
                    if (response.data.code === 100) {
                        // 关闭模态框
                        $('#addModal').modal('hide');
                        // 发送ajax请求来到最后一页
                        let page = this.pageInfo.pageNum;
                        let pageCount = Math.ceil((this.pageInfo.total + 1) / this.pageInfo.pageSize);
                        this.goBackPage(page, pageCount, "add");
                    } else if (response.data.code === 200) {
                        // 有那个字段的错误信息就显示那个字段的
                        let employeeNameInput = this.$refs.employeeName;
                        let emailInput = this.$refs.email;
                        if (undefined !== response.data.data.failMap.email) {
                            // 显示错误信息
                            this.showValidateMessage(emailInput, "error", response.data.data.failMap.email);
                        }
                        if (undefined !== response.data.data.failMap.employeeName) {
                            // 显示错误信息
                            this.showValidateMessage(employeeNameInput, "error", response.data.data.failMap.employeeName);
                        }
                    }
                });
            },
            // 修改员工信息
            updateEmployees() {
                let emailInput = this.$refs.updateEmail;
                let regEmail = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/g;
                if (!regEmail.test(this.updateEmployee.email)) {
                    this.showValidateMessage(emailInput, "error", "邮件格式不合法");
                    return false;
                } else {
                    this.showValidateMessage(emailInput, "success", "");
                }
                // 发送ajax请求更新员工信息
                axios({
                    method: 'PUT',
                    url: `http://localhost:8080/SSM/employee/${this.updateEmployee.employeeId}`,
                    params: {
                        email: this.updateEmployee.email,
                        gender: this.updateEmployee.gender,
                        departmentId: this.updateEmployee.departmentId
                    }
                }).then(response => {
                    // 关闭模态框
                    $('#updateModal').modal('hide');
                    // 重新跳转到当前页面
                    this.goBackPage(this.pageInfo.pageNum);
                });

            },
            // 删除员工信息
            deleteEmployeeById(event) {
                let employeeId = event.currentTarget.getAttribute("data-delete-id");
                let employeeName = event.currentTarget.parentElement.parentElement.childNodes[4].textContent;
                if (confirm(`确认要删除【${employeeName}】吗`)) {
                    axios({
                        method: 'DELETE',
                        url: `http://localhost:8080/SSM/employee/${employeeId}`,
                    }).then(response => {
                        // 跳转到当前页面
                        let page = this.pageInfo.pageNum;
                        let pageCount = Math.ceil((this.pageInfo.total - 1) / this.pageInfo.pageSize);
                        this.goBackPage(page, pageCount, "delete");
                    });
                }

            },
            // 批量删除员工信息
            deleteEmployeeMore() {
                let checkArr = this.$refs.check;
                let checkParentElement = null;
                let employeeNameArr = [];
                let employeeIdArr = [];
                let index = 0;
                for (let i = 0; i < checkArr.length; i++) {
                    if (checkArr[i].checked) {
                        checkParentElement = checkArr[i].parentElement.parentElement;
                        employeeIdArr[index] = checkParentElement.childNodes[2].textContent;
                        employeeNameArr[index] = checkParentElement.childNodes[4].textContent;
                        index++;
                    }
                }
                if (employeeIdArr.length === 0 || employeeIdArr === null) {
                    alert("尚未选择要删除的员工");
                    return false;
                }
                if (confirm(`确认要删除【${employeeNameArr.toString()}】吗`)) {
                    axios.delete(`http://localhost:8080/SSM/employee/${employeeIdArr.toString()}`).then(response => {
                        // 回到当前页面
                        let page = this.pageInfo.pageNum;
                        let pageCount = Math.ceil((this.pageInfo.total - employeeIdArr.length) / this.pageInfo.pageSize);
                        this.goBackPage(page, pageCount, "delete");
                        // 清空勾选框
                        let checkArr = this.$refs.check;
                        this.$refs.checkAll.checked = false;
                        for (let i = 0; i < checkArr.length; i++) {
                            checkArr[i].checked = false;
                        }

                    }), error => {
                        console.log(error);
                    }
                }

            },
            // 回到指定页码的页面
            goBackPage(page, pageCount, type) {
                // pageCount 删除或添加后的页码总数
                // page：要跳转到的页码
                // type：执行操作的类型
                if ("delete" === type) {
                    page = (page > pageCount) ? pageCount : page;
                    page = (page < 1) ? 1 : page;
                } else if ("add" === type) {
                    page = (page > pageCount) ? page : pageCount;
                }
                axios.get(`http://localhost:8080/SSM/employeeList?pageNumber=${page}`).then(response => {
                    this.pageInfo = response.data.data.employeePageInfo;
                    this.employees = response.data.data.employeePageInfo.list;
                }) , error => {
                    console.log("请求失败：", error.message);
                }
            },
            // 全选/全不选
            isCheckAll() {
                // 如果勾选了全选按钮，则列表中的都勾选
                // 获取里表中的所有勾选按钮
                let checkArr = this.$refs.check;
                for (let i = 0; i < checkArr.length; i++) {
                    checkArr[i].checked = this.$refs.checkAll.checked;
                }
            },
            // 取消全选(至少有一个没有勾选)
            oneCheck() {
                let checkArr = this.$refs.check;
                let count = 0;
                for (let i = 0; i < checkArr.length; i++) {
                    if (checkArr[i].checked) {
                        count++;
                    }
                }
                if (count === checkArr.length) {
                    this.$refs.checkAll.checked = true;
                } else {
                    this.$refs.checkAll.checked = false;
                }
            },
            // 首页
            firstPage(event) {
                axios.get(`http://localhost:8080/SSM/employeeList?pageNumber=1`).then(response => {
                    this.pageInfo = response.data.data.employeePageInfo;
                    this.employees = response.data.data.employeePageInfo.list;
                }) , error => {
                    console.log("请求失败：", error.message);
                }
                event.preventDefault();
            },
            // 尾页
            endPage(event) {
                axios.get(`http://localhost:8080/SSM/employeeList?pageNumber=${this.pageInfo.pages}`).then(response => {
                    this.pageInfo = response.data.data.employeePageInfo;
                    this.employees = response.data.data.employeePageInfo.list;
                }) , error => {
                    console.log("请求失败：", error.message);
                }
                event.preventDefault();
            },
            // 上一页
            previous(event) {
                axios.get(`http://localhost:8080/SSM/employeeList?pageNumber=${this.pageInfo.pageNum - 1}`).then(response => {
                    this.pageInfo = response.data.data.employeePageInfo;
                    this.employees = response.data.data.employeePageInfo.list;
                }) , error => {
                    console.log("请求失败：", error.message);
                }
                event.preventDefault();
            },
            // 下一页
            next(event) {
                axios.get(`http://localhost:8080/SSM/employeeList?pageNumber=${this.pageInfo.pageNum + 1}`).then(response => {
                    this.pageInfo = response.data.data.employeePageInfo;
                    this.employees = response.data.data.employeePageInfo.list;
                }) , error => {
                    console.log("请求失败：", error.message);
                }
                event.preventDefault();
            },
            // 分页导航
            navigatePage(navigatePageNumber, event) {
                axios.get(`http://localhost:8080/SSM/employeeList?pageNumber=${navigatePageNumber}`).then(response => {
                    this.pageInfo = response.data.data.employeePageInfo;
                    this.employees = response.data.data.employeePageInfo.list;
                }) , error => {
                    console.log("请求失败：", error.message);
                }
                event.preventDefault();
            }
        }
    });
</script>
</body>
</html>